package com.example.nettypractice.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.net.InetSocketAddress;


/**
 * 客户端启动流程
 */
public class FirstNettyClient {
    private final String host;
    private final int port;

    public FirstNettyClient(String host, int port){
        this.host = host;
        this.port = port;
    }
    public void start() throws InterruptedException {
        // 事件处理，连接，读写数据等
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 创建Bootstrap实例对应客户端实例
            Bootstrap b = new Bootstrap();

            b.group(group)
                    // 指定数据传输channel
                    .channel(NioSocketChannel.class)
                    // 绑定服务端地址和端口
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch){
                            // 注入对象编码器和解码器
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                            ch.pipeline().addLast(new FirstNettyClientHandler());
                        }
                    });
            // 连接服务器
            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
